const { logInfo, getFileList, parseFile, readFileContent, writeJsonFile, processTemplate, hasChinese, processJs } = require("./utils");
const { writeFileSync } = require("node:fs");
const { whitelistDirs, whitelistFiles, CONFIG } = require("./config");

logInfo('开始处理vue文件模板部分，请耐心等待...')

const fileList = getFileList(CONFIG.FILE_TYPES);
logInfo(`共找到 ${fileList.length} 个文件`);
fileList.forEach((file) => {
  const path = file.replaceAll('\\', '/');
  if (whitelistDirs && whitelistDirs.some(dir => path.includes(dir))) {
    return
  }
  if (whitelistFiles && whitelistFiles.includes(path)) {
    return
  }
  if (path.includes(".min.js")) {
    return
  }
  const content = readFileContent(file);
  const ext = path.split(".").pop();
  if (ext === 'vue') {
    // 获取文件顶部注释
    let headComment = '';
    if (content.startsWith('<!--')) {
      headComment = content.match(/<!--[\s\S]*?-->/)[0];
    }
    const { descriptor } = parseFile(content, file);
    const { script } = descriptor;
    if (script && script.content && hasChinese(script.content)) {
      const code = processJs(script.content, file)
      script.content = code;
      console.log("🚀 ~ fileList.forEach ~ code:", code)
      const styles = descriptor.styles.map(({ content, lang, scoped, src }) => {
        const langProp = lang ? `lang=\"${lang}\"` : "";
        const scopedProp = scoped ? `scoped` : "";
        return `<style ${langProp} ${scopedProp}>\n${content}\n</style>`;
      }).join("\n");
      const newContent = [
        headComment,
        descriptor.template ? `<template>${descriptor.template.content}</template>` : "",
        descriptor.script ? `<script>${code}</script>` : "",
        styles,
      ].join("\n");
      writeFileSync(file, newContent);
      logInfo(`已处理并写入: ${file}`);
    }
  }
})